/*
 * Copyright (c) csii.com.cn 2016 zhaojin
 */

package com.csii.ssm.interceptor;

import com.csii.ssm.context.ModeControllerUtil;
import com.csii.ssm.core.CommonDict;
import com.csii.ssm.exception.CoreRuntimeException;
import com.csii.ssm.exception.CoreRuntimeExceptionDict;
import com.csii.ssm.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 针对请求方式的不同做相应的过滤处理
 *
 * @author zhaojin 15398699939@163.com
 * @create 2016-04-13-下午3:24
 */

public class HandlerRequestViewInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("#{mvcContext['app.contextpath']}")
    protected String APP_CONTEXTPATH;

    @Value("#{mvcContext['app.cors.origin']}")
    protected String APP_CORS_ORIGIN;

    @Value("#{mvcContext['app.cors.allowcredentials']}")
    protected String APP_CORS_ALLOWCREDENTIALS;

    @Value("#{mvcContext['app.cors.allowmethods']}")
    protected String APP_CORS_ALLOWMETHODS;

    @Value("#{mvcContext['app.cors.allowheaders']}")
    protected String APP_CORS_ALLOWHEADERS;

    @Value("#{mvcContext['app.cors.maxage']}")
    protected String APP_CORS_MAXAGE;

    private static final String ACCEPT = "Accept";

    //*/* IE这样传
    private static final List<String> HTML_ACCEPTS = Arrays.asList(new String[]{"text/html", "*/*"});

    private String resPath;//前端使用的资源跟路径

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accept = request.getHeader(ACCEPT);
        logger.debug("===客户端的 Accept: {} ===", accept);
        request.setAttribute(CommonDict.REQ_ACCEPT, accept);
        request.setAttribute(CommonDict.REMOTE_IP_ADDR, CommonUtil.getRemoteIPAddr(request));


        String userAgentFalg = request.getHeader("user-agent");
        logger.debug("===客户端的 user-agent: {} ===", accept);

        //校验客户端的accept
        if (StringUtils.isBlank(accept)) {
            throw new CoreRuntimeException(CoreRuntimeExceptionDict.ERROR_NOT_ALLOWED_TO_ACCESS);
        }

        if (userAgentFalg.contains("MSIE")) {
            request.setAttribute(CommonDict.CLIENT_EXPLOER, CommonDict.IE);
        } else if (userAgentFalg.contains("Chrome")) {
            request.setAttribute(CommonDict.CLIENT_EXPLOER, CommonDict.CHROME);
        } else if (userAgentFalg.contains("Safari")) {
            request.setAttribute(CommonDict.CLIENT_EXPLOER, CommonDict.SAFARI);
        } else {
            request.setAttribute(CommonDict.CLIENT_EXPLOER, CommonDict.OTHER);
        }
        logger.debug("===客户端浏览器是: {}", request.getAttribute(CommonDict.CLIENT_EXPLOER));

        //CORS
        response.setHeader(CommonDict.CORSACAO, APP_CORS_ORIGIN);
        response.setHeader(CommonDict.CORSACAC, APP_CORS_ALLOWCREDENTIALS);
        response.setHeader(CommonDict.CORSACAM, APP_CORS_ALLOWMETHODS);
        response.setHeader(CommonDict.CORSACAH, APP_CORS_ALLOWHEADERS);
        response.setHeader(CommonDict.CORSACMA, APP_CORS_MAXAGE);

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

//        if (null != modelAndView) {
//
//            Map<String, Object> modelMap = modelAndView.getModel();
//            String accept = request.getHeader(ACCEPT);
//            request.setAttribute(CommonDict.APP_MODE, ModeControllerUtil.MODE);//设置应用的开发模式
//            for (String jaccept : HTML_ACCEPTS) {
//                if (Arrays.asList(accept.split(",")).contains(jaccept)) {
//                    String viewName = modelAndView.getViewName();//如:/h5/tobacco/shanxiqrcode/pre
//                    //约定jsp对应的js脚本目录结构相同,提供给前端动态加载使用,而且是相对路径
//                    request.setAttribute(CommonDict.VIEW_PAIRED_SCRIPT_PATH, viewName.startsWith("/") ? viewName.substring(1) : viewName);
//                    logger.debug("viewPairedScriptPath: {}", viewName);
//                    break;
//                }
//            }
//            //根据不同的模式做一些处理
//            switch (ModeControllerUtil.MODE) {
//                case CommonDict.MODE_DEV:
//                    //设置资源路径
//                    resPath = request.getContextPath() + CommonDict.STATICRES;
//                    break;
//                case CommonDict.MODE_TEST:
//                    resPath = request.getContextPath() + CommonDict.BUILDRES;
//                    break;
//                case CommonDict.MODE_PRO:
//                    resPath = request.getContextPath() + CommonDict.BUILDRES;
//                    break;
//            }
//            request.setAttribute(CommonDict.RESPATH, resPath);
//
//            logger.info("返回给前端的model数据:{}", modelAndView);
//        }

        super.postHandle(request, response, handler, modelAndView);
    }


}
